package com.yangye.pisystem.service.impl;

import com.yangye.picommon.core.service.impl.BaseServiceImpl;
import com.yangye.picommon.exception.PiException;
import com.yangye.picommon.utils.JwtTokenUtil;
import com.yangye.picommon.utils.TreeUtil;
import com.yangye.pisystem.dao.SysMenuMapper;
import com.yangye.pisystem.domain.SysMenu;
import com.yangye.pisystem.dto.SysMenuDTO;
import com.yangye.pisystem.service.SysMenuService;
import com.yangye.pisystem.vo.SysMenuVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yangye
 * @date 2019/8/6
 */
@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Override
	public SysMenuVO findById(Long id) {
		return dao.selectById(id);
	}

	@Override
	public List<SysMenu> findSubMenus(Long parentId) {
		SysMenu queryModel = new SysMenu();
		queryModel.setParentId(parentId);
		return dao.select(queryModel);
	}

	@Override
	public List<SysMenuDTO> listTree() {
		List<SysMenu> sysMenus = dao.selectAll();
		List<SysMenuDTO> list = new ArrayList<>();
		for (SysMenu sysMenu : sysMenus) {
			SysMenuDTO sysMenuDTO = new SysMenuDTO();
			BeanUtils.copyProperties(sysMenu, sysMenuDTO);
			list.add(sysMenuDTO);
		}

		List<SysMenuDTO> tree = TreeUtil.parseTree(list);
		return tree;
	}

	@Override
	public List<SysMenuDTO> listTreeByCurrentUser(String token) {
		String username = jwtTokenUtil.getUsernameFromToken(token);
		List<SysMenuDTO> sysMenuDTOS = this.listMenusByUsername(username);
		// 过滤按钮
		List<SysMenuDTO> menus = sysMenuDTOS.stream().filter(v -> !StringUtils.equals(v.getType(), "2")).collect(Collectors.toList());
		List<SysMenuDTO> tree = TreeUtil.parseTree(menus);
		return tree;
	}

	@Override
	public void remove(Long id) {
		// 校验菜单是否为空
		List<SysMenu> subMenus = this.findSubMenus(id);
		if (!CollectionUtils.isEmpty(subMenus)) {
			throw new PiException("当前菜单不为空，不能删除");
		}
		super.remove(id);
	}

	@Override
	public List<SysMenuDTO> listMenusByUsername(String username) {
		return dao.listMenusByUsername(username);
	}
}
